<template>
  <div class="app-container">
    <div class="head-container">
      <el-form :inline="true" :model="queryParams" ref="queryForm" size="small">
        <el-form-item label="车牌号码" prop="carNumber">
          <el-input
            v-model="queryParams.carNumber"
            placeholder="请输入车牌号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入场时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="success" icon="el-icon-printer" size="mini" @click="printReport">打印报表</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 统计信息区域 -->
      <div class="statistics-info" style="margin: 15px 0; padding: 10px; background-color: #f5f5f5; border-radius: 5px;">
        <el-tag type="info">总记录数：{{ total }} 条</el-tag>
        <el-tag type="success" style="margin-left: 10px;">当前页总金额：¥{{ totalAmount.toFixed(2) }}</el-tag>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="carList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="carNumber" label="车牌号码" width="120" />
      <el-table-column prop="entryTime" label="入场时间" width="180" :formatter="dateFormat" />
      <el-table-column prop="exitTime" label="出场时间" width="180" :formatter="dateFormat" />
      <el-table-column prop="parkingDuration" label="停车时长" width="120" />
      <el-table-column prop="amount" label="缴费金额" width="100" />
      <el-table-column prop="paymentStatus" label="缴费状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.paymentStatus === '已缴费'" type="success">已缴费</el-tag>
          <el-tag v-else type="danger">未缴费</el-tag>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listPrecords } from '@/api/system/precords.js'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/ruoyi.js'

export default {
  name: 'HistoryCar',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      carList: [],
      total: 0,
      totalAmount: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNumber: ''
      },
      dateRange: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 将前端查询参数映射到后端期望的字段名
    getList() {
      this.loading = true
      
      // 创建映射后的查询参数，将前端字段名转换为后端期望的字段名
      const backendParams = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      
      // 映射车牌号码：前端carNumber -> 后端license
      if (this.queryParams.carNumber) {
        backendParams.license = this.queryParams.carNumber
      }
      
      // 映射时间范围：前端dateRange -> 后端的开始和结束时间（使用后端期望的参数名）
      if (this.dateRange && this.dateRange.length > 0) {
        backendParams.startTime = this.dateRange[0]
        backendParams.endTime = this.dateRange[1]
      }
      
      // 使用映射后的参数调用API
      listPrecords(backendParams).then(response => {
        this.carList = response.rows
        this.total = response.total
        // 计算当前页的总金额
        this.totalAmount = response.rows.reduce((sum, record) => sum + (record.amount || 0), 0)
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.handleQuery()
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return this.parseTime(date)
    },
    // 打印报表方法
    printReport() {
      // 显示加载状态
      this.loading = true
      
      // 创建临时查询参数，获取所有数据（不进行分页）
      const printParams = {
        // 映射字段名
        pageNum: 1,
        pageSize: 9999 // 设置一个大的值来获取所有数据
      }
      
      // 映射车牌号码
      if (this.queryParams.carNumber) {
        printParams.license = this.queryParams.carNumber
      }
      
      // 映射时间范围
      if (this.dateRange && this.dateRange.length > 0) {
        printParams.startTime = this.dateRange[0]
        printParams.endTime = this.dateRange[1]
      } else {
        printParams.startTime = undefined
        printParams.endTime = undefined
      }
      
      // 获取数据
      listPrecords(printParams).then(response => {
        const allRecords = response.rows
        this.loading = false
        
        // 创建打印窗口
        this.createPrintWindow(allRecords)
      }).catch(error => {
        this.loading = false
        this.$message.error('获取打印数据失败')
        console.error('获取打印数据失败:', error)
      })
    },
    
    // 创建打印窗口
    createPrintWindow(records) {
      const printWindow = window.open('', '_blank')
      
      // 格式化时间范围显示
      let timeRangeText = '全部时间'
      if (this.dateRange && this.dateRange.length > 0) {
        timeRangeText = `${this.dateRange[0]} 至 ${this.dateRange[1]}`
      }
      
      // 计算汇总数据
      const totalAmount = records.reduce((sum, record) => sum + (record.amount || 0), 0)
      const paidCount = records.filter(record => record.paymentStatus === '已缴费').length
      const unpaidCount = records.filter(record => record.paymentStatus !== '已缴费').length
      
      // 构建打印内容
      const printContent = `
        <html>
        <head>
          <title>停车记录报表</title>
          <style>
            body {
              font-family: Arial, sans-serif;
              font-size: 12px;
              margin: 20px;
            }
            h1 {
              text-align: center;
              color: #333;
              font-size: 24px;
              margin-bottom: 20px;
            }
            .report-info {
              margin-bottom: 20px;
              text-align: right;
            }
            .summary {
              margin: 20px 0;
              padding: 10px;
              background-color: #f5f5f5;
              border: 1px solid #ddd;
              font-weight: bold;
            }
            table {
              width: 100%;
              border-collapse: collapse;
            }
            th, td {
              border: 1px solid #ddd;
              padding: 8px;
              text-align: left;
            }
            th {
              background-color: #f2f2f2;
              font-weight: bold;
            }
            tr:nth-child(even) {
              background-color: #f9f9f9;
            }
            .paid {
              color: green;
            }
            .unpaid {
              color: red;
            }
          </style>
        </head>
        <body>
          <h1>停车记录报表</h1>
          <div class="report-info">
            <p>查询时间范围: ${timeRangeText}</p>
            <p>生成时间: ${new Date().toLocaleString()}</p>
          </div>
          
          <div class="summary">
            <p>总记录数: ${records.length} 条 | 已缴费: ${paidCount} 条 | 未缴费: ${unpaidCount} 条 | 总金额: ¥${totalAmount.toFixed(2)}</p>
          </div>
          
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>车牌号码</th>
                <th>入场时间</th>
                <th>出场时间</th>
                <th>停车时长</th>
                <th>缴费金额</th>
                <th>缴费状态</th>
              </tr>
            </thead>
            <tbody>
              ${records.map((record, index) => `
                <tr>
                  <td>${index + 1}</td>
                  <td>${record.carNumber || '-'}</td>
                  <td>${parseTime(record.entryTime)}</td>
                  <td>${parseTime(record.exitTime)}</td>
                  <td>${record.parkingDuration || '-'}</td>
                  <td>¥${(record.amount || 0).toFixed(2)}</td>
                  <td class="${record.paymentStatus === '已缴费' ? 'paid' : 'unpaid'}">${record.paymentStatus}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </body>
        </html>
      `
      
      // 写入打印内容
      printWindow.document.write(printContent)
      printWindow.document.close()
      
      // 等待内容加载完成后打印
      setTimeout(() => {
        printWindow.print()
        // printWindow.close() // 可选：自动关闭窗口
      }, 500)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>